﻿using System.Threading;
using System.Threading.Tasks;
using Apache.IoTDB;
using Iot.Shared.Path;
using Iot.TimingDatabase.Helper;
using Iot.TimingDatabase.Models;
using Mediator;

namespace Iot.TimingDatabase.Event;

public sealed class IotDbDataSetQueryHandler(SessionPool session, IotDbConversion conversion)
    : IRequestHandler<IotDbDataSetQuery, IotDbDataSet>
{
    public async ValueTask<IotDbDataSet> Handle(IotDbDataSetQuery request, CancellationToken cancellationToken)
    {
        // 使用Task.Run异步执行查询操作
        // IotDb  库代码里面存在一步转同步的 类似于
        // Task.ConfigureAwait(false).GetAwaiter().GetResult()
        //在UI线程中执行同步操作会导致线程阻塞，因此使用Task.Run来避免这个问题
        return await Task.Run(async () =>
        {
            // 使用using语句确保资源正确释放
            using var historicalData = await session.ExecuteQueryStatementAsync(request.Sql);
            // 使用转换器将查询结果转换为数据集
            return conversion.ToDataSet(historicalData, request.BasicsPath);
        }, cancellationToken);
    }
}

public sealed class IotDbQuery(ISender sender)
{
    public ValueTask<IotDbDataSet> Query(string sql, DevicePath? basicsPath = null)
    {
        return sender.Send(new IotDbDataSetQuery(sql, basicsPath));
    }
}